package com.wowangz.cms.systemmanage.report.api;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.wowangz.cms.common.pojo.AjaxDataEntity;
import com.wowangz.cms.common.utils.SysConstant;
import com.wowangz.cms.component.datagrid.pojo.DataGrid;
import com.wowangz.cms.component.datagrid.pojo.DataResult;
import com.wowangz.cms.component.datagrid.pojo.DataStyle;
import com.wowangz.cms.component.datagrid.pojo.PangingParam;
import com.wowangz.cms.component.datagrid.utils.DataTypeConstant;
import com.wowangz.cms.component.datagrid.utils.PangingTools;
import com.wowangz.cms.syscore.IssTransactionContainer;
import com.wowangz.cms.syscore.api.BaseController;
import com.wowangz.cms.syscore.api.JSONFactory;
import com.wowangz.cms.syscore.utils.MessageResourcesUtils;
import com.wowangz.cms.syscore.utils.ServletUtils;
import com.wowangz.cms.systemmanage.report.pojo.Report;
import com.wowangz.cms.systemmanage.report.service.ReportService;


@Scope("prototype")
@Controller
public class ReportController extends BaseController{

	private static Logger logger = LoggerFactory.getLogger(ReportController.class);
	
	/**
	 * 点击菜单"报表维护"显示“报表维护”列表
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/systemmanage/report/queryReportList.web")
	public String queryReportList(HttpServletRequest request, HttpServletResponse response, Model model) {
		
		return "/WEB-INF/jsp/systemmanage/report/reportList";
	}
	
	/**
	 * 打开“报表维护”列表加载列表数据
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping(value = "/systemmanage/report/queryReportListInfoDataGrid.json")
	public void queryReportListInfoDataGrid(HttpServletRequest request, HttpServletResponse response, Model model) {
		PangingParam pangingParam = null;
		DataResult dataResult = new DataResult();
		DataGrid dataGrid = null;

		try {
			pangingParam = (PangingParam) ServletUtils.getParametersToBaseEntity(request, PangingParam.class);
			HashMap<String, Object> map = (HashMap) ServletUtils.getParametersToHashMap(request);
			dataGrid = new DataGrid();
			dataGrid.setPangingParam(pangingParam);

			map.put("startrow", dataGrid.getStartrow());
			map.put("endrow", dataGrid.getEndrow());
			map.put("rows", dataGrid.getRows());
			map.put("sort", dataGrid.getSort());
			map.put("order", dataGrid.getOrder());
			map.put("statusid", SysConstant.RecordStatus.VALID);

			ReportService reportService = (ReportService) IssTransactionContainer.getInstance(ReportService.class, false);
			long resultCount = reportService.findResultCount(map);
			List<Report> resultList = reportService.findResultList(map);

			DataStyle dataStyle = new DataStyle();
			dataStyle.setPageIndex(pangingParam.getPage());
			dataStyle.setDataCount(resultCount);
			dataStyle.setDataList(resultList);

			dataStyle.addDepict("id", DataTypeConstant.LONG);
			dataStyle.addDepict("reportname", DataTypeConstant.STRING);
			dataStyle.addDepict("reporturl", DataTypeConstant.STRING);
			dataStyle.addDepictByFunction("usedstatus", SysConstant.CommonUsedStatus.class, "getName", new Class[]{long.class});
			dataResult = PangingTools.buildResultPagerInfo(dataStyle);

			if (pangingParam.getReportExportType() == 0) {
				response.getWriter().write(JSONFactory.toJSONString(dataResult, userContext));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 跳转报表添加页面
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/systemmanage/report/toAddReport.web")
	public String toAddReport(HttpServletRequest request, HttpServletResponse response, Model model) {
		return "/WEB-INF/jsp/systemmanage/report/reportAdd";
	}
	
	/**
	 * 新增报表
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/systemmanage/report/addReport.web", method = { RequestMethod.GET, RequestMethod.POST })
	public String addReport(HttpServletRequest request, HttpServletResponse response, Model model) {
		ReportService reportService = (ReportService) IssTransactionContainer.getInstance(ReportService.class, true);
		Report report = (Report) ServletUtils.getParametersToBaseEntity(request, Report.class);
		try {
			report.setInputtime(new Date());
			report.setInputuserid(userContext.getLoginUser().getId());
			report.setModifytime(new Date());
			report.setModifyuserid(userContext.getLoginUser().getId());
			report.setStatusid(SysConstant.RecordStatus.VALID);
			report.setUsedstatus(SysConstant.CommonUsedStatus.STOP);
			reportService.add(report);
			userContext.setInfoMessage(MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert1"));
			userContext.setCloseWindow(true);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "/WEB-INF/jsp/systemmanage/report/reportAdd";
	}
	
	@RequestMapping(value = "/systemmanage/report/validattionReport.json", method = { RequestMethod.GET, RequestMethod.POST })
	public void validattionReport(HttpServletRequest request, HttpServletResponse response, Model model) {
		AjaxDataEntity ajaxDataEntity = new AjaxDataEntity();
		try {
			StringBuffer errorMsg = new StringBuffer();
			HashMap<String, Object> map = new HashMap<String, Object>();
			Report report = (Report) ServletUtils.getParametersToBaseEntity(request, Report.class);
			
			ReportService reportService = (ReportService) IssTransactionContainer.getInstance(ReportService.class, true);
			map.put("statusid", SysConstant.RecordStatus.VALID);
			if(null != report.getId()){
				map.put("id", report.getId());
			}
			map.put("reportname", report.getReportname());
			if(!reportService.validationReport(map)){
				errorMsg.append(MessageResourcesUtils.getMessage(request, "systemmanage.report.reportAdd.alert"));
			}
			map.remove("reportname");
			
			map.put("reporturl", report.getReporturl());
			if(!reportService.validationReport(map)){
				errorMsg.append(MessageResourcesUtils.getMessage(request, "systemmanage.report.reportAdd.alert1"));
			}
			map.remove("reporturl");
			
			if(StringUtils.isNotEmpty(errorMsg.toString())){
				userContext.setErrorMessage(errorMsg.toString());
			}
			response.getWriter().write(JSONFactory.toJSONString(ajaxDataEntity, userContext));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 跳转修改报表信息页面
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/systemmanage/report/toUpdateReport.web")
	public String toUpdateReport(HttpServletRequest request, HttpServletResponse response, Model model) {
		try {
			String reportId = getRequest().getParameter("id");
			ReportService reportService = (ReportService) IssTransactionContainer.getInstance(ReportService.class, true);
			Report report = reportService.findReportById(reportId);
			model.addAttribute("report", report);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "/WEB-INF/jsp/systemmanage/report/reportUpdate";
	}
	
	/**
	 * 修改报表
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/systemmanage/report/updateReport.web", method = { RequestMethod.GET, RequestMethod.POST })
	public String updateReport(HttpServletRequest request, HttpServletResponse response, Model model) {
		ReportService reportService = (ReportService) IssTransactionContainer.getInstance(ReportService.class, true);
		Report report = (Report) ServletUtils.getParametersToBaseEntity(request, Report.class);
		try {
			report.setModifytime(new Date());
			report.setModifyuserid(getUserContext().getLoginUser().getId());
			reportService.update(report);
			userContext.setInfoMessage(MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert1"));
			userContext.setCloseWindow(true);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "/WEB-INF/jsp/systemmanage/report/reportUpdate";
	}
	
	/**
	 * 报表启用
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping(value = "/systemmanage/report/reportStart.json", method = { RequestMethod.GET, RequestMethod.POST })
	public void reportStart(HttpServletRequest request, HttpServletResponse response, Model model) {
		ReportService reportService = (ReportService) IssTransactionContainer.getInstance(ReportService.class, true);
		AjaxDataEntity ajaxDataEntity = new AjaxDataEntity();
		Report report = new Report();
		try {
			String reportids = getRequest().getParameter("reportids");
			String[] ids = reportids.split(",");
			for(int i =0;i<ids.length;i++){
				report.setId(Long.parseLong(ids[i]));
				report.setUsedstatus(SysConstant.CommonUsedStatus.START);
				report.setModifytime(new Date());
				report.setModifyuserid(getUserContext().getLoginUser().getId());
				reportService.reportStart(report);
			}
			userContext.setInfoMessage(MessageResourcesUtils.getMessage(request, "systemmanage.report.reportlist.start"));
			response.getWriter().write(JSONFactory.toJSONString(ajaxDataEntity, userContext));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 报表停用
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping(value = "/systemmanage/report/reportStop.json", method = { RequestMethod.GET, RequestMethod.POST })
	public void reportStop(HttpServletRequest request, HttpServletResponse response, Model model) {
		ReportService reportService = (ReportService) IssTransactionContainer.getInstance(ReportService.class, true);
		AjaxDataEntity ajaxDataEntity = new AjaxDataEntity();
		Report report = new Report();
		try {
			String reportids = getRequest().getParameter("reportids");
			String[] ids = reportids.split(",");
			for(int i =0;i<ids.length;i++){
				report.setId(Long.parseLong(ids[i]));
				report.setUsedstatus(SysConstant.CommonUsedStatus.STOP);
				report.setModifytime(new Date());
				report.setModifyuserid(getUserContext().getLoginUser().getId());
				reportService.reportStart(report);
			}
			userContext.setInfoMessage(MessageResourcesUtils.getMessage(request, "systemmanage.report.reportlist.stop"));
			response.getWriter().write(JSONFactory.toJSONString(ajaxDataEntity, userContext));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 删除的省信息
	 * @param request
	 * @param response
	 * @param model
	 *//*
	@RequestMapping(value = "/systemmanage/province/deleteProvince.json", method = { RequestMethod.GET, RequestMethod.POST })
	public void deleteProvince(HttpServletRequest request, HttpServletResponse response, Model model) {
		AjaxDataEntity ajaxDataEntity = new AjaxDataEntity();
		try {
			Long provinceId = Long.valueOf(getRequest().getParameter("id"));
			CityService cityService = (CityService) IssTransactionContainer.getInstance(CityService.class, true);
			List<City> list = cityService.findCityByProvinceId(provinceId);
			if(list == null || list.size() == 0){
				Province province = new Province();
				province.setId(provinceId);
				province.setStatusid(SysConstant.RecordStatus.INVALID);
				ProvinceService provinceService = (ProvinceService) IssTransactionContainer.getInstance(ProvinceService.class, false);
				provinceService.update(province);
				userContext.setInfoMessage(MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert3"));
			}else{
				userContext.setInfoMessage(MessageResourcesUtils.getMessage(request, "systemmanage.province.provinceList.alert1"));
			}
			response.getWriter().write(JSONFactory.toJSONString(ajaxDataEntity, userContext));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}*/
}
